package org.eiahe.hr.attendance.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.common.core.utils.MapstructUtils;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.eiahe.hr.attendance.domain.Holiday;
import org.eiahe.hr.attendance.domain.bo.HolidayBo;
import org.eiahe.hr.attendance.domain.vo.HolidayVo;
import org.eiahe.hr.attendance.mapper.HolidayMapper;
import org.eiahe.hr.attendance.service.IHolidayService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 节假日服务实现
 *
 * @author zhangnn
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HolidayServiceImpl implements IHolidayService {

    private final HolidayMapper baseMapper;

    private static final String HOLIDAY_API_URL = "https://timor.tech/api/holiday/year/";

    @Override
    public HolidayVo queryById(Long holidayId) {
        return baseMapper.selectVoById(holidayId);
    }

    @Override
    public List<HolidayVo> queryList(HolidayBo bo) {
        LambdaQueryWrapper<Holiday> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public TableDataInfo<HolidayVo> queryPageList(HolidayBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Holiday> lqw = buildQueryWrapper(bo);
        Page<HolidayVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    private LambdaQueryWrapper<Holiday> buildQueryWrapper(HolidayBo bo) {
        LambdaQueryWrapper<Holiday> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getYear() != null, Holiday::getYear, bo.getYear());
        lqw.like(StringUtils.isNotBlank(bo.getHolidayName()), Holiday::getHolidayName, bo.getHolidayName());
        lqw.eq(StringUtils.isNotBlank(bo.getIsCompensatory()), Holiday::getIsCompensatory, bo.getIsCompensatory());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Holiday::getStatus, bo.getStatus());
        lqw.orderByAsc(Holiday::getHolidayDate);
        return lqw;
    }

    @Override
    public Boolean insertByBo(HolidayBo bo) {
        Holiday add = MapstructUtils.convert(bo, Holiday.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setHolidayId(add.getHolidayId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(HolidayBo bo) {
        Holiday update = MapstructUtils.convert(bo, Holiday.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    private void validEntityBeforeSave(Holiday entity) {
        // 检查同一天是否已经存在节假日记录
        if (entity.getHolidayDate() != null) {
            LambdaQueryWrapper<Holiday> lqw = Wrappers.lambdaQuery();
            lqw.eq(Holiday::getHolidayDate, entity.getHolidayDate());
            if (entity.getHolidayId() != null) {
                lqw.ne(Holiday::getHolidayId, entity.getHolidayId());
            }
            Long count = baseMapper.selectCount(lqw);
            if (count > 0) {
                throw new RuntimeException("该日期已存在节假日记录");
            }
        }
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 同步指定年份的节假日数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer syncHolidaysByYear(Integer year) {
        try {
            String url = HOLIDAY_API_URL + year;
            String response = HttpUtil.get(url);

            if (StringUtils.isBlank(response)) {
                throw new RuntimeException("调用节假日API失败,返回数据为空");
            }

            JSONObject jsonObject = JSONUtil.parseObj(response);
            Integer code = jsonObject.getInt("code");

            if (code == null || code != 0) {
                throw new RuntimeException("调用节假日API失败: " + jsonObject.getStr("message"));
            }

            JSONObject holiday = jsonObject.getJSONObject("holiday");
            if (holiday == null || holiday.isEmpty()) {
                log.warn("{}年无节假日数据", year);
                return 0;
            }

            List<Holiday> holidays = new ArrayList<>();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            // 遍历所有节假日
            for (String key : holiday.keySet()) {
                JSONObject dayInfo = holiday.getJSONObject(key);

                Boolean isHoliday = dayInfo.getBool("holiday");
                String name = dayInfo.getStr("name");
                Integer wage = dayInfo.getInt("wage");
                String dateStr = dayInfo.getStr("date");

                Holiday entity = new Holiday();
                entity.setHolidayDate(LocalDate.parse(dateStr, formatter));
                entity.setHolidayName(name);
                entity.setYear(year);
                entity.setStatus("0");

                boolean isCompensatory = (wage != null && wage == 1) || Boolean.FALSE.equals(isHoliday);
                entity.setIsCompensatory(isCompensatory ? "1" : "0");

                holidays.add(entity);
            }

            if (holidays.isEmpty()) {
                return 0;
            }

            // 删除该年份的旧数据
            LambdaQueryWrapper<Holiday> deleteLqw = Wrappers.lambdaQuery();
            deleteLqw.eq(Holiday::getYear, year);
            baseMapper.delete(deleteLqw);

            // 批量插入新数据
            boolean success = baseMapper.insertBatch(holidays);
            return success ? holidays.size() : 0;

        } catch (Exception e) {
            log.error("同步{}年节假日数据失败", year, e);
            throw new RuntimeException("同步节假日数据失败: " + e.getMessage());
        }
    }

    /**
     * 批量导入节假日
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer batchImportHolidays(List<HolidayBo> holidays) {
        if (holidays == null || holidays.isEmpty()) {
            return 0;
        }

        List<Holiday> entities = new ArrayList<>();
        for (HolidayBo bo : holidays) {
            Holiday entity = MapstructUtils.convert(bo, Holiday.class);
            entities.add(entity);
        }

        boolean success = baseMapper.insertBatch(entities);
        return success ? entities.size() : 0;
    }
}
